import React from 'react';
import { WingBlank, WhiteSpace, InputItem, List, Button, Toast } from 'antd-mobile';
import { connect } from 'react-redux';
import {createForm} from 'rc-form';
import { withClient } from '../../hoc';

import {getParams} from '../../utils/crmUtils';

import {setToken, setUserInfo} from '../../redux/modules/token';

import './login.sass';
import { Promise } from 'core-js';

const mapStateToProps = (state) => ({
  access_token: state.token.access_token,
  userInfo: state.token.userInfo,
})

@withClient
@createForm()
@connect(mapStateToProps, {setToken, setUserInfo})
export default class Login extends React.Component {
  constructor(props) {
    super(props);
    // console.log(props, getParams(props.location.search));
    const params = props.location.search ? getParams(props.location.search) : null;
    if(params.invalid_token){
      Toast.fail('登录过期，请重新登录')
    }
    this.state={
      params: params.invalid_token ? {headImage:props.userInfo.headImage, openid: props.userInfo.openid} : params,
      loading: false,
    }
  }
  onSubmit = () => {
    this.props.form.validateFields(async (err, values) => {
      if(!err){
        // this.setState({loading: true});
        let res;
        try {
          res = await this.props.client.post(`/cloud-auth/oauth/token`,{'grant_type':'password', ...values})
        } catch (error) {
          if(error.error === 'invalid_grant'){
            Toast.fail('账号或密码错误');
          }
        }
        // const res = await this.props.client.post(`/api_auth`,{'grant_type':'password', ...values})

        if(res && res.access_token && res.token_type){
          const {params} = this.state;
          const [response, userInfo] = await Promise.all([
            this.props.client.post(`/crm/api/mobile/bind`,{openid: params.openid, headImage: params.headImage, refreshToken: res.refresh_token, access_token: res.access_token}),
            this.props.client.post(`/crm/api/mobile/personalinfo`,{access_token: res.access_token}),
          ])
          console.log(userInfo);
          if(userInfo){
            this.props.setUserInfo(userInfo.data);
          }
          // return;
          if(Number(response.errcode) === 0 && Number(response.status) === 0){
            this.props.setToken(res.access_token);
            this.props.history.push('/features');
          }else{
            this.setState({loading: false});
            Toast.fail(response.msg);
          }
        }else{
          this.setState({loading: false});
        }
        console.log(res);
      }else{
        if(!values.username){
          Toast.fail('请输入账号');
          return ;
        }
        if(!values.password){
          Toast.fail('请输入密码');
          return ;
        }
      }
    })
  }
  componentDidMount(){
    if(__CLIENT__){
      setTimeout(() => {
        !this.state.params && Toast.fail('请从公众号内点击进入');
      },0)
    }
  }
  render() {
    const {getFieldDecorator} = this.props.form;
    const {loading, params} = this.state;
    return (
      <div className="login-container">
        <div className="login-content">
          <WingBlank size="lg">
            <div className="icon-lg">JoYoWo</div>
            <WhiteSpace />
            <WhiteSpace />
            <WhiteSpace />
          </WingBlank>
          <WingBlank size="lg">
            <div className="text-small">100%在线人力资源服务平台</div>
          </WingBlank>
          <WingBlank size="lg">
            <div
              style={{
                padding: '0.6rem 1.2rem'
              }}
            >
              <List className="global-list">
                {getFieldDecorator('username', {
                  rules: [
                    {
                      required: true,
                      message: '请输入账号!'
                    }
                  ],
                  validateFirst: true,
                })(<InputItem clear placeholder="请输入账号">
                  账号
                </InputItem>)}
                {getFieldDecorator('password', {
                  rules: [
                    {
                      required: true,
                      message: '请输入密码!'
                    }
                  ],
                  validateFirst: true,
                })(<InputItem type='password' clear placeholder="请输入密码">
                  密码
                </InputItem>)}
              </List>
              <WhiteSpace size='lg' />
              <WhiteSpace size='lg' />
              <Button disabled={!params || loading} onClick={this.onSubmit} size="small">登录</Button>
            </div>
          </WingBlank>
        </div>
      </div>
    );
  }
}
